package com.xchb.im.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xchb.im.common.config.RabbitMQConst;
import com.xchb.im.common.enums.MsgType;
import com.xchb.im.common.enums.NocticeTypeEnum;
import com.xchb.im.common.pojo.ChatMsg;
import com.xchb.im.common.pojo.NoticeContent;
import com.xchb.im.server.service.MessageService;
import com.xchb.im.server.service.UserService;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.CharSet;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author XDD
 * @project muchat
 * @date 2021/7/23
 * @description Good Good Study,Day Day Up.
 */
@Service
public class MessageServiceImpl implements MessageService {


    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private UserService userService;

    @Override
    public boolean send(ChatMsg chatMsg) {
        if(chatMsg==null || MsgType.privat.getType()==chatMsg.getType()){
            NoticeContent notice = new NoticeContent();
            notice.setAction(NocticeTypeEnum.CHAT.type);
            notice.setChatMsg(chatMsg);

            //入库
            userService.saveMsg(chatMsg);
            //推送
            this.push(notice);

            return true;
        }

        return false;
    }

    private void push(NoticeContent content) {
        amqpTemplate.send(RabbitMQConst.CHAT_MESSAGE_EXCHANGE,RabbitMQConst.CHAT_MESSAGE_ROUTINGKEY,
                MessageBuilder.withBody(JSONObject.toJSONBytes(content)).build());
    }
}
